package com.tocici.recommender;


import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.LongPrimitiveIterator;
import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.impl.similarity.UncenteredCosineSimilarity;
import org.apache.mahout.cf.taste.model.JDBCDataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class MusicRecommender {
    private final Recommender recommender;

    public MusicRecommender(DataSource dataSource) throws TasteException, SQLException {
        JDBCDataModel mySQLJDBCDataModel = new MySQLJDBCDataModel(dataSource, "user_behavior", "user_id", "music_id", "score",null);
        UserSimilarity similarity = new PearsonCorrelationSimilarity(mySQLJDBCDataModel);

        // 最近邻算法
        UserNeighborhood neighborhood = new NearestNUserNeighborhood(100, similarity, mySQLJDBCDataModel);
        System.out.println("dataSource = " + dataSource);
        System.out.println("neighborhood.getUserNeighborhood(1896048234612269058L) = " + Arrays.toString(neighborhood.getUserNeighborhood(1896048234612269058L)));
        LongPrimitiveIterator userIDs = mySQLJDBCDataModel.getUserIDs();
        while (userIDs.hasNext()){
            System.out.println("=============================");
            long l = userIDs.nextLong();
            LongPrimitiveIterator otherUserIDs = mySQLJDBCDataModel.getUserIDs();
            while (otherUserIDs.hasNext()){
                long otherUserIds = otherUserIDs.nextLong();
                System.out.println(String.format("用户：%s与用户：%s的相似度为%s",l,otherUserIds,similarity.userSimilarity(l,otherUserIds)));
            }
        }

        // 构建推荐器
        this.recommender = new GenericUserBasedRecommender(
            mySQLJDBCDataModel,
            neighborhood,
            similarity
        );
    }

    public List<RecommendedItem> recommend(Long userId, int count) throws TasteException {
        List<RecommendedItem> recommend = recommender.recommend(userId, count);
        System.out.println("recommend = " + recommend);
        return recommend;
    }
}
